var map = null;
var myLocMarker = null;
var myCurrentAsset = null;
var myLatLng = null;
var situationLatLng = null;
var sensorMarkers = [];
var buildingMarkers = [];
var buildingFireMarkers = [];
var buildingAttachmentMarkers = [];
var buildingStatusMarkers = [];
var buildingPeopleMarkers = [];
var pathMarkers = [];
var entryPointMarkers = [];
var safespotMarkers = [];
var missionPlan = null;
var buildingData = null;
var pathData = null;
var safespotData = null;
var mission = null;
var missionRoute = null;
var locationMarker = null;
var rectangle = null;
var longClickTimer = null;
var jsonRetrieveCount = 0;
var pathFirePolys = [];
var frLocationMarkers = [];
var frAttachmentsMarkers = [];
var myLocIcon = 'img/blue_dot.png';
var buildingIcon = 'img/white_marker.png';
var activeBuildingIcon = 'img/light_green_marker.png';
var peopleIcon = 'img/people.png';
var safespotIcon = 'img/safespot.png';
var buildingAttachmentIcon = 'img/attachment.png';
var attachmentIcons = [
    "img/responder_message.png",
    "img/responder_image.png",
    "img/responder_message_image.png"
];
var bldStatusIcons = [
	"img/cleared.png",
	"img/dropped.png"
];
var fireIcons = [
	"img/fire_minimal.png",
	"img/fire_moderate.png",
	"img/fire_severe.png"
];
var responderIcons = [
	"img/responder_red.png",
	"img/responder_green.png",
	"img/responder_blue.png",
	"img/responder_orange.png",
	"img/responder_aqua.png",
	"img/responder_lavender.png"	
];
function loadScript() {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
	document.body.appendChild(script);
}
window.onload = loadScript;
function setLocationMarkerListeners(marker) {
	google.maps.event.addListener(marker, 'click', function() {
		if (window.android) {
			window.android.showLocationDialog(marker.getPosition().lat(), marker.getPosition().lng());
		} else {
			alert(marker.getPosition());
		}
	});
}
function onLongMapClick(event) {
	var latLng = event.latLng;
	locationMarker.setMap(null);
	locationMarker = new google.maps.Marker({
		position: latLng,
		map: map
	});
	setLocationMarkerListeners(locationMarker);
	if (window.android) {
		window.android.toastLocationInfo(latLng.lat(), latLng.lng());
	}
}
function setupLongMapClickListeners() {
	google.maps.event.addListener(rectangle, 'click', function(event) {
	});
	google.maps.event.addListener(rectangle, 'mousedown', function(event) {
		longClickTimer = setTimeout(function() { onLongMapClick(event); }, 1000);
	});
	google.maps.event.addListener(rectangle, 'mouseup', function(event) {
		clearTimeout(longClickTimer);
	});
	google.maps.event.addListener(rectangle, 'mouseout', function(event) {
		clearTimeout(longClickTimer);
	});
	google.maps.event.addListener(map, 'drag', function() {
		clearTimeout(longClickTimer);
	});	
}
function setAssetMarkerListeners(marker) {
	google.maps.event.addListener(marker, 'click', function(event) {
		if (window.android) {
			window.android.showAssetDialog(marker.getTitle());
		} else {
			alert(marker.getTitle());
		}
	});
	google.maps.event.addListener(marker, 'dblclick', function() {
	});
}
function setResponderMarkerListeners(marker) {
	google.maps.event.addListener(marker, 'click', function(event) {
		if (window.android) {
			window.android.showResponderDialog(marker.getTitle());
		} else {
			alert(marker.getTitle());
		}
	});
	google.maps.event.addListener(marker, 'dblclick', function() {
	});
}
function setResponderMessageMarkerListeners(marker) {
	google.maps.event.addListener(marker, 'click', function(event) {
		if (window.android) {
			window.android.showResponderAttachmentDialog("" + marker.getTitle());
		} else {
			alert(marker.getTitle());
		}
	});
	google.maps.event.addListener(marker, 'dblclick', function() {
	});
}
function onJsonDataRetrieved() {
	jsonRetrieveCount++;
	if (!window.android) {
		if (jsonRetrieveCount == 3) {
			getMissionPlanData('json/mission-plan-data-1.json', true);
		}
	}
}
function retrieveBuildingData(showIt, showPerimeterPoints) {
	$.getJSON('json/building-data.json', function(data) {
		buildingData = data;
		onJsonDataRetrieved();
		if(showIt) {
			for (var i in buildingData) {
				var lat = buildingData[i].centerPoint.latitude;
				var lng = buildingData[i].centerPoint.longitude;
				var latLng = new google.maps.LatLng(lat, lng);
				var marker = new google.maps.Marker({
					position: latLng,
					title:  buildingData[i].id,
					icon: buildingIcon,
					map: map
				});
				setAssetMarkerListeners(marker);
				buildingMarkers[marker.getTitle()] = marker;
				var entryPoints = buildingData[i].entryPoints;
				for (var j in entryPoints) {
					var epos = new google.maps.LatLng(entryPoints[j].latitude, entryPoints[j].longitude);
					var emarker = new google.maps.Marker({
						position: epos,
						title: buildingData[i].id + " entry " + j,
						icon: 'img/blue_dot.png',
						map: map
					});
					entryPointMarkers.push(emarker);
				}
	
				var perimeterPoints = buildingData[i].perimeterPoints;
				var previousLatLng = null;
				var firstLatLng = null;
				
				var polyOptions = {
						strokeColor: '#99ffff', //color,
					    strokeOpacity: 1.0,
					    strokeWeight: 2
					};
	
				for (var j in perimeterPoints) {
					var latLng = new google.maps.LatLng(perimeterPoints[j].latitude, perimeterPoints[j].longitude);
					if(firstLatLng == null) {
						firstLatLng = latLng;
					}
	
					if(previousLatLng != null) {
						var poly = new google.maps.Polyline(polyOptions);
						poly.getPath().push(latLng);
						poly.getPath().push(previousLatLng);
						poly.setMap(map);					
					}
					
					
					if(showPerimeterPoints) {
						var marker = new google.maps.Marker({
							position: latLng,
							title: buildingData[i].id + " perimeter point " + j,
							icon: 'img/small_blue_dot.png',
							map: map
						});
					}
					previousLatLng = latLng;
				}
				var poly = new google.maps.Polyline(polyOptions);
				poly.getPath().push(previousLatLng);
				poly.getPath().push(firstLatLng);
				poly.setMap(map);					
			}
		}
	});	
}
function getPathData(showIt, showIntersections, showCenterLabels) {
	$.getJSON('json/path-data.json', function(data) {
		pathData = data;
		onJsonDataRetrieved();

		if(showIt) {
			var count = 0;
			for (var i in pathData) {
				var id = pathData[i].id;
				var sLat = pathData[i].p1.latitude;
				var sLng = pathData[i].p1.longitude;
				var eLat = pathData[i].p2.latitude;
				var eLng = pathData[i].p2.longitude;
	
				//var rsLat = sLat + Math.random() / 20000;
				//var rsLng = sLng + Math.random() / 20000;
				//var reLat = eLat + Math.random() / 20000;
				//var reLng = eLng + Math.random() / 20000;
				
				var sLatLng = new google.maps.LatLng(sLat, sLng);
				var eLatLng = new google.maps.LatLng(eLat, eLng);
				var mLatLng = new google.maps.LatLng((sLat + eLat) / 2.0, (sLng + eLng) / 2.0 );
	
				if(showIntersections) {
					var marker = new google.maps.Marker({
						position: sLatLng,
						title: id,
						icon: 'img/red_dot.png',
						map: map
					});
					var marker = new google.maps.Marker({
						position: eLatLng,
						title: id,
						icon: 'img/red_dot.png',
						map: map
					});
				}
				
				if(showCenterLabels) {
					var marker = new google.maps.Marker({
						position: mLatLng,
						title: id,
						map: map
					});
					pathMarkers.push(marker);
				}
				var color = null;
				switch (count) {
				case 0:
					color = '#FF0000';
					count++;
					break;
				case 1:
					color = '#00FF00';
					count++;
					break;
				case 2:
					color = '#0000FF';				
					count = 0;
					break;
				}
				var polyOptions = {
					strokeColor: '#00FF00', //color,
				    strokeOpacity: 1.0,
				    strokeWeight: 2
				};
				var poly = new google.maps.Polyline(polyOptions);
				poly.getPath().push(sLatLng);
				poly.getPath().push(eLatLng);
				poly.setMap(map);
			}
		}
	});	
}
function getSafespotData(showIt) {
	$.getJSON('json/safespot-data.json', function(data) {
		safespotData = data;
		onJsonDataRetrieved();
		
		if(showIt) {

			for (var i in safespotData) {
				var latLng = new google.maps.LatLng(
						safespotData[i].safespot.latitude, 
						safespotData[i].safespot.longitude);
				var marker = new google.maps.Marker({
					position: latLng,
					title: "Safe Spot " + i,
					icon: 'img/green_dot.png',
					map: map
				});
			}
		}
	});
}
function loadMissionPlan(data,showIt) {
	mission = data.objectives;
	
	if(showIt) {
		var polyOptions = {
				strokeColor: '#0066CC',
			    strokeOpacity: 0.5,
			    strokeWeight: 8
		};
		missionRoute = new google.maps.Polyline(polyOptions);
		var previousPoints = [];
		for (var i in mission) {
			if (mission[i].safespot != null) {
				var safespotName = mission[i].safespot;
				var lat = safespotData[safespotName].safespot.latitude;
				var lng = safespotData[safespotName].safespot.longitude;
				var latLng = new google.maps.LatLng(lat, lng);
				var marker = new google.maps.Marker({
					position: latLng,
					title: safespotName,
					icon: safespotIcon,
					map: map
				});
				var pos = new google.maps.LatLng(lat, lng);
				missionRoute.getPath().push(pos);
				previousPoints = [];
				previousPoints[0] = pos;
				setAssetMarkerListeners(marker);
				safespotMarkers.push(marker);					
			} else if (mission[i].route != null) {
				for (var j in mission[i].route) {
					var pathName = mission[i].route[j].path;
					var slat = pathData[pathName].p1.latitude;
					var slng = pathData[pathName].p1.longitude;
					var elat = pathData[pathName].p2.latitude;
					var elng = pathData[pathName].p2.longitude;
							
					var sLatLng = new google.maps.LatLng(slat, slng);
					var eLatLng = new google.maps.LatLng(elat, elng);
					var useStart = true;
					for (var k in previousPoints) {
						if(previousPoints[k].lat() == slat && previousPoints[k].lng() == slng) {
							useStart = false;
						}
					}
					
					var nextLatLng;
					var otherLatLng;
					if(useStart) {
						nextLatLng = sLatLng;
						otherLatLng = eLatLng;
						//missionRoute.getPath().length;
					} else {
						nextLatLng = eLatLng;
						otherLatLng = sLatLng;
					}
					
					if(missionRoute.getPath().getLength() > 0) {
						var lastPoint = missionRoute.getPath().getAt(missionRoute.getPath().getLength() - 1);
						if(lastPoint.lat() != otherLatLng.lat() || lastPoint.lng() != otherLatLng.lat()) {
							missionRoute.getPath().push(otherLatLng);
						}
					}
					missionRoute.getPath().push(nextLatLng);							
					previousPoints = [];
					previousPoints[0] = sLatLng;
					previousPoints[1] = eLatLng;
				}
			} else if (mission[i].building != null) {
				var buildingName = mission[i].building;
				var building = buildingData[buildingName];
				var lat = building.centerPoint.latitude;
				var lng = building.centerPoint.longitude;
				var latLng = new google.maps.LatLng(lat, lng);
				var marker = new google.maps.Marker({
					position: latLng,
					title: buildingName,
					icon: buildingIcon,
					map: map
				});
				previousPoints = [];
				var entryPoints = building.entryPoints;
				for (var j in entryPoints) {
					var latLng = new google.maps.LatLng(entryPoints[j].latitude, entryPoints[j].longitude);
					previousPoints[j] = latLng;
				}
				setAssetMarkerListeners(marker);
				buildingMarkers[marker.getTitle()] = marker;
			}
		}
		missionRoute.setMap(map);
	}	
}
function getMissionPlanData(file, showIt) {
	$.getJSON(file, function(data) {
		loadMissionPlan(data,true);
	});
}
function clearMissionRoute() {
	if (missionRoute != null) {
		missionRoute.setMap(null);
	}
}
function clearBuildingMarkers() {
	if (buildingMarkers != null) {
		for (var b in buildingMarkers) {
			buildingMarkers[b].setMap(null);
			delete buildingMarkers[b];
		}
		buildingMarkers = [];
	}
}
function clearMissionPlan() {
	clearSafespotMarkers();
	clearMissionRoute();
	clearBuildingMarkers();
	clearBuildingFireIcons();
	clearBuildingStatusMarkers();
	clearBuildingPeopleMarkers();
	clearBuildingAttachmentMarkers();
	myCurrentAsset = null;
}
function showMissionPlan(fileName) {
	if (fileName != null) {
		clearMissionPlan();
		if (jsonRetrieveCount == 3) {
			getMissionPlanData(fileName, true);
		}
	}
}
function retrieveAllJsonData() {
	retrieveBuildingData(false, false);
	getPathData(false, false, false);
	getSafespotData(false);
}
function centerAtLatLng(lat, lng) {
	var latLng = new google.maps.LatLng(lat, lng);
	map.panTo(latLng);
}
function centerAtMyLatLng() {
	map.panTo(myLatLng);
}
function updateMyLatLng() {
	if (window.android) {
		var lat = window.android.getLatitude();
		var lng = window.android.getLongitude();
		myLatLng = new google.maps.LatLng(lat, lng);
	}
	if (myLocMarker != null) {
		myLocMarker.setPosition(myLatLng);
	} else {
		myLocMarker = new google.maps.Marker({
			position: myLatLng,
			icon: myLocIcon,
			map: map
		});
		setAssetMarkerListeners(myLocMarker);
	}
}
function displayBuildingOnFire(assetId,index) {
	if (index != 0 && index != 1 && index != 2) {
		return;
	}
	if (buildingFireMarkers[assetId] != null) {
		if (buildingFireMarkers[assetId].getIcon() != fireIcons[index]) {
			buildingFireMarkers[assetId].setIcon(fireIcons[index]);
		}
	} else {
		var lat = buildingData[assetId].centerPoint.latitude;
		var lng = buildingData[assetId].centerPoint.longitude;
		var latLng = new google.maps.LatLng(lat, lng);
		var marker = new google.maps.Marker({
			position: latLng,
			title:  assetId,
			icon: fireIcons[index],
			map: map
		});
		setAssetMarkerListeners(marker);
		buildingFireMarkers[assetId] = marker;
	}
}
function clearBuildingFireIcons() {
	if (buildingFireMarkers != null) {
		for (var s in buildingFireMarkers) {
			buildingFireMarkers[s].setMap(null);
			delete buildingFireMarkers[s];
		}
		buildingFireMarkers = [];
	}	
}
function displayBuildingCleared(assetId) {
	displayBuildingStatus(assetId, 0);
}
function displayBuildingDropped(assetId) {
	displayBuildingStatus(assetId, 1);
}
function displayBuildingStatus(assetId,index) {
	if (index != 0 && index != 1) {
		return;
	}
	if (buildingStatusMarkers[assetId] != null) {
		buildingStatusMarkers[assetId].setIcon(bldStatusIcons[index]);
	} else {
		var lat = buildingData[assetId].centerPoint.latitude;
		var lng = buildingData[assetId].centerPoint.longitude;
		var latLng = new google.maps.LatLng(lat, lng);
		var marker = new google.maps.Marker({
			position: latLng,
			title:  assetId,
			icon: bldStatusIcons[index],
			map: map
		});
		setAssetMarkerListeners(marker);
		buildingStatusMarkers[assetId] = marker;
	}	
}
function clearBuildingStatusMarkers() {
	if (buildingStatusMarkers != null) {
		for (var s in buildingStatusMarkers) {
			buildingStatusMarkers[s].setMap(null);
			delete buildingStatusMarkers[s];
		}
		buildingStatusMarkers = [];
	}
}
function displaySafespotOnFire(assetId,severity) {
	for (var i in safespotMarkers) {
		if (safespotMarkers[i].getTitle() == assetId &&
				safespotMarkers[i].getIcon() != fireIcons[severity]) {
			safespotMarkers[i].setIcon(fireIcons[severity]);
			break;
		}
	}	
}
function clearSafespotMarkers() {
	if (safespotMarkers != null) {
		for (var s in safespotMarkers) {
			safespotMarkers[s].setMap(null);
			delete safespotMarkers[s];
		}
		safespotMarkers = [];
	}
}
function displayPathOnFire(assetId) {
/*
	var polyOptions = {
			strokeColor: '#00FF00', //color,
		    strokeOpacity: 1.0,
		    strokeWeight: 2
	};
	var path = new google.maps.Polyline(polyOptions);
	path.getPath().push(latLng);
	path.getPath().push(previousLatLng);	
	path.setMap(map);
	pathFirePolys.push(path);
	*/
}
function displayRouteOnFire(assetId) {
	
}
function displayAttachmentOnBuilding(assetId) {
	if (buildingAttachmentMarkers[assetId] == null) {
		var lat = buildingData[assetId].centerPoint.latitude;
		var lng = buildingData[assetId].centerPoint.longitude;
		var latLng = new google.maps.LatLng(lat, lng);
		var marker = new google.maps.Marker({
			position: latLng,
			title:  assetId,
			icon: buildingAttachmentIcon,
			map: map
		});
		setAssetMarkerListeners(marker);
		buildingAttachmentMarkers[assetId] = marker;
	}
}
function clearBuildingAttachmentMarkers() {
	if (buildingAttachmentMarkers != null) {
		for (var a in buildingAttachmentMarkers) {
			buildingAttachmentMarkers[a].setMap(null);
			delete buildingAttachmentMarkers[a];
		}
		buildingAttachmentMarkers = [];
	}
}
function displayPeopleInBuilding(assetId) {
	if (buildingPeopleMarkers[assetId] == null) {
		var lat = buildingData[assetId].centerPoint.latitude;
		var lng = buildingData[assetId].centerPoint.longitude;
		var latLng = new google.maps.LatLng(lat, lng);
		var marker = new google.maps.Marker({
			position: latLng,
			title:  assetId,
			icon: peopleIcon,
			map: map
		});
		setAssetMarkerListeners(marker);
		buildingPeopleMarkers[assetId] = marker;
	}
}
function clearBuildingPeopleMarkers() {
	if (buildingPeopleMarkers != null) {
		for (var p in buildingPeopleMarkers) {
			removePeopleInBuilding(p);
		}
		buildingPeopleMarkers = [];
	}
}
function removePeopleInBuilding(assetId) {
	if (buildingPeopleMarkers[assetId] != null) {
		buildingPeopleMarkers[assetId].setMap(null);
		delete buildingPeopleMarkers[assetId];
	}
}
function displayResponderLocation(assetId,lat,lng) {
	var latLng = new google.maps.LatLng(lat, lng);
	if (frLocationMarkers[assetId] != null) {
		frLocationMarkers[assetId].setPosition(latLng);
	} else {
		var index = genIntFromStr(assetId) % responderIcons.length;
		var marker = new google.maps.Marker({
			position: latLng,
			title:  assetId,
			icon: responderIcons[index],
			map: map
		});
		setResponderMarkerListeners(marker);
		frLocationMarkers[assetId] = marker;
	}
}
function clearAllResponderLocations() {
	for (var i in frLocationMarkers) {
		frLocationMarkers[i].setMap(null);
		delete frLocationMarkers[i];
	}
	frLocationMarkers = [];
}
function displayAttachmentOnLocation(typeId,lat,lng) {
	var latLng = new google.maps.LatLng(lat, lng);
	var latLngStr = "" + latLng;
	if (frAttachmentsMarkers[latLngStr] == null) {
		var marker = new google.maps.Marker({
			position: latLng,
			icon: attachmentIcons[typeId],
			map: map
		});
		setResponderMessageMarkerListeners(marker);
		frAttachmentsMarkers[latLngStr] = marker;
	} else if (attachmentIcons[typeId] != attachmentIcons[2]) {
		frAttachmentMarkers[latLngStr].setIcon(attachmentIcons[2]);
	}
}
function clearAllResponderAttachments() {
	for (var i in frAttachmentsMarkers) {
		frAttachmentsMarkers[i].setMap(null);
		delete frAttachmentsMarkers[i];
	}
	frAttachmentsMarkers = [];
}
function clearLocationMarker() {
	if (locationMarker != null) {
		locationMarker.setMap(null);
	}
}
function initialize() {
	if (window.android) {
		var sitlat = window.android.getSituationLat();
		var sitlng = window.android.getSituationLng();
		situationLatLng = new google.maps.LatLng(sitlat, sitlng);
	} else {
		situationLatLng = new google.maps.LatLng(38.82970, -77.30731);
	}
	var myOptions = {
		zoom: 17,
		center: situationLatLng,
		mapTypeControl: true,
		navigationControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	var sw = new google.maps.LatLng(38.82701, -77.31004);
	var ne = new google.maps.LatLng(38.83102, -77.30462);
	var bounds = new google.maps.LatLngBounds(sw, ne);
	rectangle = new google.maps.Rectangle({
		bounds: bounds,
		map: map,
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 2,
		fillOpacity: 0
	});
	locationMarker = new google.maps.Marker();
	setupLongMapClickListeners();
	retrieveAllJsonData();
}
function genIntFromStr(str) {
	var value = 0;
	for (var i in str) {
		value += str.charCodeAt(i);
	}
	return value;
}
function loadNewPlanFromString(jsonStr) {
	var data = $.parseJSON(jsonStr);
	clearMissionPlan();
	loadMissionPlan(data,true);
}
function updateMostRelevantAsset(assetId) {
	if (myCurrentAsset != null) {
		myCurrentAsset.setIcon(buildingIcon);
		myCurrentAsset = buildingMarkers[assetId];
		myCurrentAsset.setIcon(activeBuildingIcon);
	} else {
		myCurrentAsset = buildingMarkers[assetId];
		myCurrentAsset.setIcon(activeBuildingIcon);
	}
}